//
//  ZJCommentVC.m
//  这家测试项目
//
//  Created by IOS_DEVELOPER on 2017/6/29.
//  Copyright © 2017年 陈志凌. All rights reserved.
//

#import "ZJCommentVC.h"
#import "ZJCommentCell.h"
#import "ZJCommentModel.h"
#import "CQTextView.h"

@interface ZJCommentVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UITextViewDelegate>{
    float keybordHeight;
    float _curHeight;
    float _pointY;
    float heightText;//文字高度
}
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *sendBtn;
@property (weak, nonatomic) IBOutlet UIView *btLine;

@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (weak, nonatomic) IBOutlet UITextField *comtTx;
@property (strong, nonatomic) CQTextView *textView;

@property (nonatomic) NSInteger page;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation ZJCommentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    self.commentView.frame = CGRectMake(0, self.view.height - 120, SCREEN_WIDTH, 56);
    self.btLine.frame = CGRectMake(0, 0, SCREEN_WIDTH, 1);
    self.sendBtn.frame = CGRectMake(self.commentView.width - 15 - 30, 15, 30, 30);
    self.comtTx.frame = CGRectMake(8, 13, self.commentView.width - 8 - 54, self.commentView.height - 26);
    self.tableview.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height - self.commentView.height);
    
    CQTextView *textView = [[CQTextView alloc]initWithFrame:self.comtTx.frame];
    textView.textView.delegate = self;
    textView.backgroundColor = [UIColor redColor];
    [self.commentView addSubview:textView];
    textView.backgroundColor = [UIColor clearColor];
    textView.font = [UIFont systemFontOfSize:17];
    textView.placeholder = @"写评论...";
    
    self.textView = textView;
    
    
    [self.tableview registerNib:[UINib nibWithNibName:NSStringFromClass([ZJCommentCell class]) bundle:nil] forCellReuseIdentifier:@"ZJCommentCell"];
    [self.sendBtn setImage:[UIImage imageWithContentsOfFile:[Utils imgPath:@"pl_icon_fs@3x.png"]] forState:0];
    self.page = 1;
    [self requsetData];
    [self setupRefresh];
    
    UIButton* backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"nav_icon_fh"]
                forState:UIControlStateNormal];
    backButton.frame = CGRectMake(0, 0, 20, 20);
    [backButton addTarget:self
                   action:@selector(backAction)
         forControlEvents:UIControlEventTouchUpInside];
    
    backButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.navigationItem.leftBarButtonItem =
    [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    [self.tableview setSeparatorColor:[Utils colorWithHexString:@"dddddd"]];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(void)backAction{

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setupRefresh
{
    WEAK_SELF
    [self.tableview setRefreshWithHeaderBlock:nil footerBlock:^{
        STRONG_SELF
        strongSelf.page++;
        [strongSelf requsetData];
    }];

}

#pragma mark - ******************请求数据
-(void)requsetData{
    [HUD showLoading:@"加载数据中..."];
    NSDictionary *parameter = [LRNetwork requestParameter:@{@"page":@(self.page)}];
    NSString *url = [LRNetwork requestURL:@"cgi/comment_list.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        NSArray *arr = [ZJCommentModel mj_objectArrayWithKeyValuesArray:returnValue[@"comment"]];
        if (self.page == 0) {
            self.dataArray = arr.mutableCopy;
        } else {
            [self.dataArray addObjectsFromArray:arr];
        }
        if (!self.dataArray) {
            self.dataArray = arr.mutableCopy;
        }
        [self.tableview reloadData];
        [self.tableview footerEndRefreshing];
        [HUD hide];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [self.tableview footerEndRefreshing];
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        [self.tableview footerEndRefreshing];
    }];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   [tableView tableViewDisplayWitMsg:kNoDataImgName ifNecessaryForRowCount:self.dataArray.count];
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZJCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZJCommentCell"];
    ZJCommentModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZJCommentModel *model = self.dataArray[indexPath.row];
    CGFloat height = [self.tableview cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ZJCommentCell class] contentViewWidth:[Utils cellContentViewWith]];
    
    return height;;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (IBAction)sendBtn:(UIButton *)sender {
    
    if ([NSString isNullOrEmpty:self.textView.textView.text]) {
        [HUD showErrorMsg:@"内容不能为空"];
        return;
    }
    [HUD showLoading:@"评论提交中..."];
    NSDictionary *parameter = [LRNetwork requestParameter:@{@"content":self.textView.textView.text}];
    NSString *url = [LRNetwork requestURL:@"cgi/comment.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        [HUD showSucceedMsg:@"提交成功,审核中..."];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [self.tableview footerEndRefreshing];
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        [self.tableview footerEndRefreshing];
    }];
    self.textView.textView.text = @"";

}
#pragma mark - 补全分隔线左侧缺失
- (void)viewDidLayoutSubviews {
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableview setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

/** textView文本内容改变时回调 */
-(void)textViewDidChange:(UITextView *)textView{
    if (self.textView.textView.text.length >200) {

        return;
    }

    static CGFloat maxHeight =100.0f;
    CGRect frame = self.textView.textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [self.textView.textView sizeThatFits:constraintSize];
    if (size.height<=frame.size.height) {
        size.height=frame.size.height;
    }else{
        if (size.height >= maxHeight)
        {
            size.height = maxHeight;
            textView.scrollEnabled = YES;   // 允许滚动
//            self.commentView.y = self.commentView.y + 20;
        }
        else
        {
            textView.scrollEnabled = NO;    // 不允许滚动
            self.commentView.y = self.commentView.y - 20;
        }
    }
    self.textView.textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
    self.textView.frame = frame;
    self.commentView.height = size.height + 20;

    // 如果文本为空，显示placeholder
    if (textView.text.length == 0) {
        self.textView.placeholderLabel.hidden = NO;
        self.commentView.frame = CGRectMake(0, self.commentView.y , SCREEN_WIDTH, self.commentView.height);
        self.sendBtn.frame = CGRectMake(self.commentView.width - 15 - 30, 15, 30, 30);
        self.textView.frame = CGRectMake(8, 13, self.commentView.width - 8 - 54, self.commentView.height - 26);
        _curHeight = 0;
        self.textView.placeholderLabel.y = 0;
        self.textView.textView.y = self.textView.placeholderLabel.y;
    }else{
        self.textView.placeholderLabel.hidden = YES;
    }
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = 200 - comcatstr.length;
    
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = [text substringWithRange:rg];
            
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
        }
        return NO;
    }
    
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keybordHeight = keyboardRect.size.height;
    
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.commentView.y = self.view.height - self.commentView.height;
//    self.btLine.frame = CGRectMake(0, 0, SCREEN_WIDTH, 1);
    self.tableview.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height - self.commentView.height);
}
-(CABasicAnimation *)moveX:(float)time X:(NSNumber *)x
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];///.y的话就向下移动。
    animation.toValue = x;
    animation.duration = time;
    animation.removedOnCompletion = NO;//yes的话，又返回原位置了。
    //    animation.repeatCount = MAXFLOAT;
    animation.fillMode = kCAFillModeForwards;
    return animation;
}
@end
